<template>
  <div>
    <!--条件筛选-->
    <TopFilter ref="topFilter" :list="topFilterList" :cols="3" labelWidth="110" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="false"
      :onRowSelectChange="selectChange"
      :onColumnsChange="(columns) => (this.columns = columns)"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="showAddtFun()">新增</el-button>
        <el-button size="small" icon="el-icon-upload" @click="showImportFun()">导入</el-button>
      </template>
    </FilterTable>
    <BaseDialog style="min-height: 80vh" :visible.sync="showAdd" width="80vw" title="新增" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '50px' }">
      <FormPanel ref="formPanel" :list="formInfoList" labelWidth="100" :isSubmitBtn="false" @formChange="formChangeHandle"> </FormPanel>
      <div style="padding-top: 1rem"></div>
      <div
        :style="{
          position: 'absolute',
          left: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'right',
        }"
      >
        <multiuse-button @click="saveDialog" type="primary">保 存</multiuse-button>
        <multiuse-button @click="closeDialog">关闭</multiuse-button>
      </div>
    </BaseDialog>

    <!-- 编辑窗口 -->
    <Drawer :visible.sync="visibleDrawer" :title="title" :width="1000" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <add v-model="initData" :type="handleType" :rowData="formData" @close="closeAdd" @save="saveAdd" />
    </Drawer>
    <!-- 导入-->
    <BaseDialog
      style="min-height: 80vh"
      :visible.sync="showImport"
      width="80vw"
      title="图解目录批量导入"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '50px' }"
    >
      <ExcelImport ref="import" template-file-name="图解目录导入模板.xlsx" :importRules="importRules" :onComplete="importComplete" @close="showImport = false" />
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { getGraphicinfo, getGraphicModelList, getGraphicSystemList, postImport, deleteGraphicInfo, update } from '@/api/graphic/catalogue/index';
import add from './add';
import ExcelImport from '@/components/ExcelImport';
import { getUserId } from '@/assets/js/auth';

export default {
  name: 'rcatalogueManage',
  components: { add, ExcelImport },
  mixins: [dictionary],
  data() {
    return {
      importRules: [
        { prop: 'modelCode', title: '车型代码', rule: { required: true, message: '系统代码不能为空' } },
        { prop: 'modelName', title: '车型名称', rule: { required: true, message: '系统代码不能为空' } },
        { prop: 'systemCode', title: '系统代码', rule: { required: true, message: '系统代码不能为空' } },
        { prop: 'systemName', title: '系统名称', rule: { required: true, message: '系统名称不能为空' } },
        { prop: 'redianCode', title: '热点编号', rule: { required: true, message: '热点编号不能为空' } },
        { prop: 'graphicCode', title: '备件代码', rule: { required: true, message: '备件代码不能为空' } },
        { prop: 'graphicName', title: '备件名称', rule: { required: true, message: '备件名称不能为空' } },
        { prop: 'oneMenu', title: '上级代码' },
        { prop: 'unitAmount', title: '单元用量' },
        { prop: 'remarkAssembly', title: '备注' },
        // {
        //   prop: 'isSpare', title: '是否备件',
        //   rule: [
        //     {required: true, message: '是否备件不能为空'},
        //     {itemList: this.createDictList('1004')}
        //   ]
        // }
      ],
      formInfoList: this.createFormInfoList(),
      showAdd: false,
      showImport: false,
      modelName: '',
      systemName: '',
      systemCode: '',
      modelCode: '',
      okstate: '',
      topFilterList: this.createTopFilterList(),
      columns: this.createTableColumns(),
      fetchApi: getGraphicinfo,
      fetchParams: { xhrAbort: true },
      visibleDrawer: false,
      handleType: '',
      formData: {},
      title: '',
      initData: {},
      partinfos: {},
      rowSelectData: [],
      saveData: null,
    };
  },
  methods: {
    formChangeHandle(val) {
      this.saveData = val;
    },
    //取消操作
    closeDialog() {
      // this.$emit('close', {visible: false, data: this.selectedRows, type: 'close'});
      this.formInfoList.forEach((x) => {
        console.log(x);
        if (x.initialValue != '未完成') {
          x.initialValue = '';
        }
      });
      this.showAdd = false;
    },
    saveAdd() {
      // this.visibleDrawer = false;
      this.fetchParams = { ...this.fetchParams };
    },
    closeAdd() {
      this.visibleDrawer = false;
    },
    saveDialog() {
      var systemCode;
      var modelCode;
      this.formInfoList[1].itemList.forEach((x) => {
        if (x.value == this.formInfoList[1].initialValue) {
          modelCode = x.text;
        }
      });
      this.formInfoList[3].itemList.forEach((x) => {
        if (x.value == this.formInfoList[3].initialValue) {
          systemCode = x.text;
        }
      });

      this.$refs.formPanel.SUBMIT_FORM();
      let graphicAssemblyInfoDTO = {
        systemCode: systemCode,
        systemName: this.saveData.systemName,
        modelCode: modelCode,
        modelName: this.saveData.modelName,
        okstate: this.saveData.okstate,
        remark: this.saveData.remark,
      };
      this.loading = true;
      // console.log(this.saveData)
      update(graphicAssemblyInfoDTO).then((res) => {
        if (res.resultCode === 200) {
          // console.log(res)
          this.loading = false;
          this.$emit('save');
          //关闭
          this.closeDialog();
          //刷新页面
          this.fetchParams = { ...this.fetchParams };
          return this.$notify.success({ title: '提示信息', message: '保存成功' });
        } else {
          this.loading = false;
          this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
        }
      });
    },
    createFormInfoList() {
      return [
        { type: 'INPUT', label: 'ID', hidden: 'true', fieldName: 'graphicId' },
        {
          type: 'SELECT',
          label: '车型代码',
          fieldName: 'modelCode',
          placeholder: '请选择...',
          itemList: this.getGraphicModelAddArray(),
          change: (val) => {
            this.modeOnChange(val);
          },
          rules: [{ required: true, message: '请选择车型代码...', trigger: 'blur' }],
        },
        { type: 'INPUT', label: '车型名称', fieldName: 'modelName', disabled: true },
        {
          type: 'SELECT',
          label: '系统代码',
          fieldName: 'systemCode',
          placeholder: '请选择...',
          itemList: this.getGraphicSystemAddArray(),
          change: (val) => {
            this.systemOnChange(val);
          },
          rules: [{ required: true, message: '请选择系统代码...', trigger: 'blur' }],
        },
        { type: 'INPUT', label: '系统名称', fieldName: 'systemName', disabled: true },
        {
          type: 'SELECT',
          label: '完成状态',
          fieldName: 'okstate',
          placeholder: '请选择...',
          itemList: this.createDictList('3042'),
          rules: [{ required: true, message: '请选择状态...', trigger: 'blur' }],
        },
        { type: 'TEXT_AREA', label: '备注', fieldName: 'remark', selfCols: 3, maxlength: 180 },
      ];
    },
    // ADD
    showAddtFun() {
      this.showAdd = true;
    },
    modeOnChange(val) {
      this.formInfoList[2].initialValue = val;
    },
    systemOnChange(val) {
      this.formInfoList[4].initialValue = val;
    },
    // Excel更新导入
    showImportFun() {
      this.showImport = true;
    },
    //导入
    importComplete(datas, callback) {
      this.$confirm('导入会重置相应的数据，请问要确定导入吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          const errorData = [];
          datas.forEach((item, index1) => {
            const indexarr = [];
            if (item.oneMenu == '') {
              datas.forEach((i, index2) => {
                if (i.graphicCode == item.graphicCode && i.modelCode == item.modelCode && i.systemCode == item.systemCode 
                    && i.redianCode == item.redianCode && i.unitAmount == item.unitAmount && index1 !== index2) {
                  indexarr.push(index2 + 2);
                }
              });
            } else {
              datas.forEach((i, index2) => {
                if (
                  i.graphicCode == item.graphicCode &&
                  i.modelCode == item.modelCode &&
                  i.systemCode == item.systemCode &&
                  i.oneMenu == item.oneMenu &&
                  i.redianCode == item.redianCode &&
                  i.unitAmount == item.unitAmount &&
                  index1 !== index2
                ) {
                  indexarr.push(index2 + 2);
                }
              });
            }

            if (indexarr.length) {
              errorData.push({
                rownum: index1 + 2,
                errormsg: `与第${indexarr.join(',')}行图解目录信息重复`,
              });
            }
          });
          if (errorData.length) {
            callback(errorData);
          } else {
            postImport(datas).then((res) => {
              if (res.resultCode == 200) {
                if (res.data.status) {
                  this.showImport = false;
                  this.$notify.success({ title: '提示信息', message: '批量导入成功' });
                  //刷新页面
                  this.fetchParams = { ...this.fetchParams };
                  callback();
                  this.infoClose({ type: 'refresh' });
                } else {
                  callback(res.data.errorData);
                }
              } else {
                callback([{ errormsg: '服务器运行异常' }]);
              }
            });
          }
        })
        .catch(() => {
          //关闭导入
          this.showImport = false;
        });
    },
    getGraphicModelArray() {
      // debugger;
      let res = [];
      getGraphicModelList().then((response) => {
        response.data.forEach((x) => {
          res.push({ text: x.modelName, value: x.modelName });
        });
      });
      return res;
    },
    getGraphicModelAddArray() {
      // debugger;
      let res = [];
      getGraphicModelList().then((response) => {
        response.data.forEach((x) => {
          // this.fromInfo.modelName=x.modelName
          res.push({ text: x.modelCode, value: x.modelName });
        });
      });
      return res;
    },
    getGraphicSystemArray() {
      let res = [];
      getGraphicSystemList().then((response) => {
        response.data.forEach((x) => {
          res.push({ text: x.systemName, value: x.systemName });
        });
      });
      return res;
    },
    getGraphicSystemAddArray() {
      let res = [];
      getGraphicSystemList().then((response) => {
        response.data.forEach((x) => {
          res.push({ text: x.systemCode, value: x.systemName });
        });
      });
      return res;
    },
    createTopFilterList() {
      return [
        {
          type: 'SELECT',
          label: '车型名称',
          fieldName: 'modelName',
          placeholder: '请选择...',
          itemList: this.getGraphicModelArray(),
        },
        {
          type: 'SELECT',
          label: '系统名称',
          fieldName: 'systemName',
          placeholder: '请选择...',
          itemList: this.getGraphicSystemArray(),
        },
        {
          type: 'SELECT',
          label: '完成状态',
          fieldName: 'okstate',
          placeholder: '请选择...',
          itemList: this.createDictList('3042'),
        },
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          render: (props) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.editHandle(props.row, 'edit')}>
                  编辑
                </el-button>
                <el-divider direction="vertical" />
                <el-button size="mini" type="text" onClick={() => this.deleteRow(props.row)}>
                  删除
                </el-button>
              </div>
            );
          },
        },
        { title: '车型代码', dataIndex: 'modelCode', sorter: true },
        { title: '车型名称', dataIndex: 'modelName', sorter: true },
        { title: '系统代码', dataIndex: 'systemCode', sorter: true },
        { title: '系统名称', dataIndex: 'systemName', sorter: true },
        { title: '完成状态', dataIndex: 'okstate', dictItems: this.createDictList('3042'), sorter: true },
        { title: '最后修改人', dataIndex: 'updatedByName', sorter: true },
        { title: '最后修改时间', dataIndex: 'updatedAt', dateFormat: 'yyyy-MM-dd HH:mm:ss', sorter: true },
      ];
    },
    selectChange(val) {
      this.rowSelectData = val;
    },
    editHandle(row, type) {
      if (type === 'edit') {
        this.title = '编辑';
      }
      if (type === 'add') {
        this.title = '新增';
      }
      this.formData = row;
      this.handleType = type;
      this.visibleDrawer = true;
    },

    changeHandle(val) {
      let params = Object.assign({}, val, { xhrAbort: false });
      if (params.bjsycx && params.bjsycx != null && params.bjsycx.length > 0) {
        params.bjsycx = params.bjsycx.join(',');
      }
      // this.fetchParams = Object.assign({}, val);
      this.fetchParams = params;
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    deleteRow(row) {
      this.$confirm('确认要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteGraphicInfo(row.graphicId)
          .then((res) => {
            if (res.data) {
              this.$notify.success({ title: '提示信息', message: '删除成功!' });
              //刷新页面
              this.fetchParams = { ...this.fetchParams };
            } else {
              this.$notify.error({ title: '提示信息', message: '删除失败，请先删除总成内数据！' });
            }
          })
          .catch((err) => {
            this.$notify.error({ title: '提示信息', message: '删除失败，系统出错！' });
          });
      });
    },
  },
};
</script>

<style scoped></style>
